package com.youyun56.gps.android.dao;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.youyun56.gps.android.pojo.Im;
import com.youyun56.gps.android.service.LocationUploadService;

public class ImDao {

    private static ImDao imDao;
    private DatabaseHelper helper;
    private final static String[] columns = new String[] { "id", "context", "userId", "attach", "addDay" };
    private SQLiteDatabase db;
    private Context context;

    private ImDao(Context context) {
        // TODO Auto-generated constructor stub
        this.context = context;
        helper = new DatabaseHelper(context);
        this.db = helper.getWritableDatabase();
        imDao = this;
    }

    public static ImDao getInstance() {
        if (imDao != null) {
            return imDao;
        } else {
            return new ImDao(LocationUploadService.getInstance());
        }
    }

    public void saveIm(Im im) {
        ContentValues values = new ContentValues();
        // 想该对象当中插入键值对，其中键是列名，值是希望插入到这一列的值，值必须和数据库当中的数据类型一致
        values.put("context", im.getContext());
        values.put("userId", im.getUserId());
        values.put("attach", im.getAttach());
        values.put("addDay", im.getAddDay());
        db.insert(DatabaseHelper.imTableName, null, values);
    }

    public List<Im> getAllIms() {
        Cursor cursor = db.query(DatabaseHelper.imTableName, columns, null, null, null, null, "");
        List<Im> ims = new ArrayList<Im>();
        while (cursor.moveToNext()) {
            Long id = cursor.getLong(cursor.getColumnIndex("id"));
            String context = cursor.getString(cursor.getColumnIndex("context"));
            Long userId = cursor.getLong(cursor.getColumnIndex("userId"));
            String attach = cursor.getString(cursor.getColumnIndex("attach"));
            String addDay = cursor.getString(cursor.getColumnIndex("addDay"));
            Im im = new Im();
            im.setId(id);
            im.setContext(context);
            im.setUserId(userId);
            im.setAttach(attach);
            im.setAddDay(addDay);
            ims.add(im);
        }
        return ims;
    }

    public void delImById(String id) {
        db.delete(DatabaseHelper.imTableName, "id=?", new String[] { id });
    }

}
